/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package XMLParsing;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author mida
 */
public class DomOntologieUnmarshaller {

    public DomOntologieUnmarshaller() {
    }

    // -----
    public Ontologie unmarshallOntologie(Node rootNode) {
        Ontologie c = new Ontologie();

        Node n;
        NodeList nodes = rootNode.getChildNodes();

        for (int i = 0; i < nodes.getLength(); i++) {
            n = nodes.item(i);

            if (n.getNodeType() == Node.ELEMENT_NODE) {

                if (n.getNodeName().equals("groupe")) {
                    c.addGroupe(unmarshallGroupe(n));

                } else {
                    // unexpected element in Catalog
                }
            } else {
                // unexpected node-type in Catalog
            }
        }
        return c;
    }

    // -----
    Groupe unmarshallGroupe(Node groupeNode) {
        Groupe m = new Groupe();

        if (groupeNode.hasAttributes() == true) {
            m.setNum(Integer.parseInt(unmarshallAttribute(groupeNode, "num", "unknown")));
        }

        Node n;
        NodeList nodes = groupeNode.getChildNodes();

        for (int i = 0; i < nodes.getLength(); i++) {
            n = nodes.item(i);

            if (n.getNodeType() == Node.ELEMENT_NODE) {

                if (n.getNodeName().equals("classe")) {
                    m.addClasse(new ontClasse(unmarshallText(n)));
                } else if (n.getNodeName().equals("objectProperty")) {
                    m.addObjectProperty(new ObjectProperty(unmarshallText(n)));
                } else if (n.getNodeName().equals("dataTypeProperty")) {
                    m.addDataTypeProperty(new DataTypeProperty(unmarshallText(n)));

                } else {
                    // unexpected element in Magazine
                }
            } else {
                // unexpected node-type in Magazine
            }
        }
        return m;
    }

    // -----
    String unmarshallText(Node textNode) {
        StringBuffer buf = new StringBuffer();

        Node n;
        NodeList nodes = textNode.getChildNodes();

        for (int i = 0; i < nodes.getLength(); i++) {
            n = nodes.item(i);

            if (n.getNodeType() == Node.TEXT_NODE) {
                buf.append(n.getNodeValue());
            } else {
                // expected a text-only node!
            }
        }
        return buf.toString();
    }

    // -----
    String unmarshallAttribute(Node node,
            String name, String defaultValue) {
        Node n = node.getAttributes().getNamedItem(name);
        return (n != null) ? (n.getNodeValue()) : (defaultValue);
    }
}
